import {
    Dimension,
    GameMode,
    StructureAnimationMode,
    world,
} from "@minecraft/server";
import { Dimensions } from "@sapi-game/constants";
import { Game } from "@sapi-game/main";
import { ScriptRunner } from "@sapi-game/Runner/scriptRunner";
import { Duration } from "@sapi-game/utils";
import { EffectIds } from "@sapi-game/utils/vanila-data";
import { WereWolfOutPhase } from "@/werewolf/phases/out";
import { WereWolfPhaseView } from "@/werewolf/phaseView";

export class OutClaasicPhase extends WereWolfPhaseView<WereWolfOutPhase> {
    get outPlayer() {
        return this.state.outPlayer!;
    }

    override onAttach(): void {
        if (!this.state.outPlayer) {
            this.runner.run(this.tie.bind(this));
        } else {
            this.runner.run(this.runPhaseView.bind(this));
        }
    }

    //平局
    async tie(r: ScriptRunner) {
        this.players.title(this.outPlayer == null ? "§e§l弃票" : "§a§l平局");
        await r.wait(10);
        this.players.runCommand("title @s subtitle 没有人被驱逐");
        await r.wait(40);
        this.state.next();
    }

    //开始发射
    override async runPhaseView(r: ScriptRunner): Promise<void> {
        this.players.sendMessage(
            this.outPlayer.name + "§e得票最多，即将被小狗发射台发射"
        );
        await r.wait(20);
        world.structureManager.place(
            "发射台",
            Dimensions.Overworld,
            { x: -53, y: -60, z: -108 },
            {
                animationSeconds: 1,
                animationMode: StructureAnimationMode.Layers,
            }
        );
        world.structureManager.place("发射架空", Dimensions.Overworld, {
            x: -54,
            y: -53,
            z: -109,
        });
        await r.wait(50);
        //发射
        const sub = this.tpToLaunchPos();
        Dimensions.Overworld.runCommand("setblock -51 -58 -108 redstone_block");
        await r.wait(2);
        Dimensions.Overworld.runCommand("setblock -51 -58 -108 barrier");
        await r.wait(80);
        //停止tp
        if (sub) this.unsubscribe(sub);
        this.players.sendMessage(
            `§e${this.outPlayer.name}§o§b变成了绚丽的烟花`
        );
        await r.wait(40);
        this.outPlayer.player?.setGameMode(GameMode.Spectator);
        await r.wait(40);
        this.state.next();
    }

    tpToLaunchPos() {
        return this.subscribe(
            Game.events.interval,
            () => {
                this.outPlayer.player?.teleport({ x: -51, y: -55, z: -106 });
                this.outPlayer.player?.addEffect(EffectIds.Resistance, 60, {
                    amplifier: 100,
                    showParticles: false,
                });
                Dimensions.Overworld.spawnParticle(
                    "minecraft:water_evaporation_bucket_emitter",
                    { x: -51, y: -55, z: -107 }
                );
            },
            new Duration(2)
        );
    }
}
